package commons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import database.DeviceProfileDAO;
import database.UserProfileDAO;

import activities.MainActivity;
import activities.StartScreen;
import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

public class AsyncTaskPage extends AsyncTask<String, Integer, String> {
	private StringBuilder builder;
	private ProgressDialog dialog;
	MainActivity main;
	private String method = "";
	int i = 0;
	private Context mContext;
	long startTime, diffTime;

	public AsyncTaskPage(Context ctx, String method) {
		main = (MainActivity) ctx;
		dialog = new ProgressDialog(ctx);
		mContext = ctx;
		this.method = method;
		main.btn.setText("Stop");
	};

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		if (method.equals("useranddevice")) {
		}
		if (method.equals("find")) {
			Log.d("find", "dasdads");
			dialog.setTitle("Getting data");
			dialog.setMessage("Wating...");
			dialog.setIcon(R.drawable.arrow_down_float);
			dialog.setProgress(0);
			dialog.setCancelable(false);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.show();
		}
		startTime = System.currentTimeMillis();

	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		if (dialog.isShowing())
			dialog.setProgress(values[0]);
	}

	@Override
	protected String doInBackground(String... URL) {
		// TODO Auto-generated method stub

		builder = new StringBuilder();
		String line = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(URL[0]);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				while ((line = reader.readLine()) != null) {
					// diffTime = (System.currentTimeMillis() - startTime) /
					// 1000;
					// if (diffTime > 3) {
					// this.cancel(true); //cancel because waste of time
					// }
					i++;
					builder.append(line.toString()).append("\n");
					if (dialog.isShowing())
						publishProgress((int) i * 100 / 30000);
				}
			} else {
				Log.e("Getter", "Failed to download!");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}

		return new String(builder.toString());
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		List<Integer> listV1 = new ArrayList<Integer>(), listV2 = new ArrayList<Integer>(), listV3 = new ArrayList<Integer>();
		List<String> listTime = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat(
				"dd.MM.yy-HH:mm:ss:SSS");
		if (method.equals("find")) {
			if (result.equals("")) {
				main.setResult(listV1, listV2, listV3, listTime);
			} else {

				JSONArray jaray = null;
				JSONObject jObject;
				try {
					jObject = new JSONObject(result);
					jaray = jObject.getJSONArray("datarecord");
					int v1 = 0, v2 = 0, v3 = 0;
					for (int i = 0; i < jaray.length(); i++) {
						Long time = jaray.getJSONObject(i).getLong(
								"timeOfDevice");
						Date d = new Date(time);
						
						String formattedDate = sdf.format(d);
						// Log.d("date", formattedDate);
						listTime.add(formattedDate);
						v1 = (Integer) jaray.getJSONObject(i).get("v1");
						listV1.add(v1);
						v2 = (Integer) jaray.getJSONObject(i).get("v2");
						listV2.add(v2);
						v3 = (Integer) jaray.getJSONObject(i).get("v3");
						listV3.add(v3);

					}
					main.setResult(listV1, listV2, listV3, listTime);
				} catch (Exception e) {
					Log.d("exception", e.getMessage());
				}
			}
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
		}
	}
}
